import axios from 'axios'
import {Message,Notification } from 'element-ui'
import router from '../router/index'
import store from '@/store';
import {baseURL} from '@/utils/setting'
// function loading() {
//     let loading = Loading.service({  // 加载遮罩
//         lock: true,
//         text: '加载中...',
//         spinner: 'el-icon-loading',
//         background: 'rgba(0, 0, 0, 0.1)'
//     })
// }
// 创建axios实例
const axiosInstance = axios.create({
    baseURL: baseURL,
    // timeout: 1200000 // 请求超时时间，毫秒（默认2分钟
})

// 前置拦截
axiosInstance.interceptors.request.use(config => {
    if(store.state.user.token){
        config.headers['Authorization'] = store.state.user.token
    }
    return config;
}, function (error) {
    console.log('error!!!');
    return Promise.reject(error);
})

axiosInstance.interceptors.response.use(response => {
        let res = response.data;
        console.log("=================")
        console.log(res)
        console.log("=================")

        if (res.code >= 200 && res.code<300) {
            if(response.config.method == "post"){
                if(res.code == 200){
                    Message.success(res.message, {duration: 3 * 1000});
                }else if(res.code == 201){
                    Message(res.message, {duration: 3 * 1000});
                }else{
                    Notification.error({
                        title: '错误',
                        message: res.message
                    });
                }
            }
            return response
        } else if(res.code === 401){
            Message.error(res.message, {duration: 3 * 1000})
            store.dispatch('user/clean').then(()=>{
                console.log("router.push(/login)")
                router.push("/login")
            })
            // location.reload() // 为了重新实例化vue-router对象 避免bug
            return Promise.reject(res.message)
        }else {
            Message.error(res.message, {duration: 3 * 1000})
            return Promise.reject(res.message)
        }
    }
)

export default axiosInstance